#
#  Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
import os
import sys
import logging
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from flask import Blueprint, Flask
from werkzeug.wrappers.request import Request
from flask_cors import CORS
from flasgger import Swagger
from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer

from api.db import StatusEnum
from api.db.db_models import close_connection
from api.db.services import UserService
from api.utils import CustomJSONEncoder, commands

from flask_session import Session
from flask_login import LoginManager
from api import settings
from api.utils.api_utils import server_error_response
from api.constants import API_VERSION

__all__ = ["app"]

# 为Flask的Request对象添加一个便捷属性json，用于强制解析JSON请求数据（忽略MIME类型）
Request.json = property(lambda self: self.get_json(force=True, silent=True))

# 创建Flask应用实例，使用当前模块的名称作为应用名
app = Flask(__name__)

# Add this at the beginning of your file to configure Swagger UI
# 定义Swagger UI配置，设置API文档相关参数和路径
"""
"rule_filter": lambda rule: True,  # 包含所有路由规则
"model_filter": lambda tag: True,  # 包含所有模型定义
"static_url_path": "/flasgger_static",   # 静态资源路径
"swagger_ui": True,                      # 启用Swagger UI界面
"specs_route": "/apidocs/",              # API文档访问路径
"""
swagger_config = {
    "headers": [],
    "specs": [
        {
            "endpoint": "apispec",
            "route": "/apispec.json",
            "rule_filter": lambda rule: True,  # Include all endpoints
            "model_filter": lambda tag: True,  # Include all models
        }
    ],
    "static_url_path": "/flasgger_static",
    "swagger_ui": True,
    "specs_route": "/apidocs/",
}

# 初始化Flasgger扩展，集成Swagger UI到Flask应用中
"""
"title": "RAGFlow API",           # API文档标题
"description": "",                # 描述信息（此处为空）
"version": "1.0.0",               # API版本号
"""
swagger = Swagger(
    app,
    config=swagger_config,
    template={
        "swagger": "2.0",
        "info": {
            "title": "RAGFlow API",
            "description": "",
            "version": "1.0.0",
        },
        "securityDefinitions": {
            "ApiKeyAuth": {"type": "apiKey", "name": "Authorization", "in": "header"}
        },
    },
)

# 启用CORS跨域支持，允许携带凭证，缓存预检请求2592000秒
CORS(app, supports_credentials=True, max_age=2592000)
# 禁用URL末尾斜杠的严格检查，使 /api 和 /api/ 被视为相同
app.url_map.strict_slashes = False
# 使用自定义JSON编码器处理序列化操作
app.json_encoder = CustomJSONEncoder
# 全局异常处理器，捕获未处理的异常并返回统一错误响应
app.errorhandler(Exception)(server_error_response)

## convince for dev and debug
## 开发调试用途的配置项（已注释），如禁用登录验证
# app.config["LOGIN_DISABLED"] = True
# 设置会话非永久有效
app.config["SESSION_PERMANENT"] = False
# 设置会话类型为文件系统存储
app.config["SESSION_TYPE"] = "filesystem"
# 设置最大请求体大小，默认为1GB
app.config["MAX_CONTENT_LENGTH"] = int(
    os.environ.get("MAX_CONTENT_LENGTH", 1024 * 1024 * 1024)
)

# 初始化Session扩展，启用服务器端会话管理
Session(app)
# 创建LoginManager实例，用于用户身份验证管理
login_manager = LoginManager()
# 将LoginManager绑定到Flask应用
login_manager.init_app(app)

# 注册命令行指令到Flask应用中，用于执行自定义CLI命令
commands.register_commands(app)


# 搜索指定目录下的页面模块路径，查找符合命名规范的Python文件
def search_pages_path(pages_dir):
    # 查找所有以“_app.py”结尾的非隐藏文件，匹配应用主模块
    app_path_list = [
        path for path in pages_dir.glob("*_app.py") if not path.name.startswith(".")
    ]
    # 查找sdk子目录下所有非隐藏的.py文件，用于支持SDK相关接口
    api_path_list = [
        path for path in pages_dir.glob("*sdk/*.py") if not path.name.startswith(".")
    ]
    # 合并两个列表：优先处理主应用模块，再处理SDK模块
    app_path_list.extend(api_path_list)
    # 返回符合条件的所有模块路径列表
    return app_path_list


# 注册页面函数，用于动态加载模块并注册蓝图（Blueprint），设置对应的URL前缀
def register_page(page_path):
    # 构建完整路径，用于日志或调试信息显示
    path = f"{page_path}"

    # 从文件路径中提取模块名称：去掉文件后缀，并移除_app后缀作为模块名
    page_name = page_path.stem.removesuffix("_app")
    # 使用api目录后的路径构建模块的完整导入路径（dot notation）
    module_name = ".".join(
        page_path.parts[page_path.parts.index("api"): -1] + (page_name,)
    )

    # 从指定路径加载模块规范（spec），用于动态导入模块
    spec = spec_from_file_location(module_name, page_path)
    # 创建一个新的模块对象
    page = module_from_spec(spec)
    # 将Flask应用实例绑定到该模块的`app`属性上
    page.app = app
    # 创建一个蓝图对象，用于组织路由逻辑
    page.manager = Blueprint(page_name, module_name)
    # 将新创建的模块加入sys.modules，使其成为已导入模块
    sys.modules[module_name] = page
    # 执行模块加载，触发模块内部的初始化逻辑
    spec.loader.exec_module(page)
    # 获取模块中定义的页面名称，若未定义则使用默认的page_name
    page_name = getattr(page, "page_name", page_name)
    # 根据系统平台判断是否为SDK路径，用于决定URL前缀格式
    sdk_path = "\\sdk\\" if sys.platform.startswith("win") else "/sdk/"
    # 根据是否为SDK路径，构造不同的URL前缀
    url_prefix = (
        f"/api/{API_VERSION}" if sdk_path in path else f"/{API_VERSION}/{page_name}"
    )

    # 将蓝图注册到Flask应用，并指定其URL前缀
    app.register_blueprint(page.manager, url_prefix=url_prefix)
    # 返回当前注册的URL前缀，供外部使用
    return url_prefix


# 定义需要扫描页面模块的目录列表：
# 1. 当前文件所在目录
# 2. api/apps 目录
# 3. api/apps/sdk 目录
pages_dir = [
    Path(__file__).parent,
    Path(__file__).parent.parent / "api" / "apps",
    Path(__file__).parent.parent / "api" / "apps" / "sdk",
]

# 遍历所有pages_dir中的目录，查找符合条件的页面模块并注册
# 对每个找到的页面调用register_page函数，收集返回的URL前缀
client_urls_prefix = [
    register_page(path) for dir in pages_dir for path in search_pages_path(dir)
]


@login_manager.request_loader
def load_user(web_request):
    jwt = Serializer(secret_key=settings.SECRET_KEY)
    authorization = web_request.headers.get("Authorization")
    if authorization:
        try:
            access_token = str(jwt.loads(authorization))
            user = UserService.query(
                access_token=access_token, status=StatusEnum.VALID.value
            )
            if user:
                return user[0]
            else:
                return None
        except Exception as e:
            logging.warning(f"load_user got exception {e}")
            return None
    else:
        return None


@app.teardown_request
def _db_close(exc):
    close_connection()
